<template>
  <div class="list-table">
    <div class=" area-header">
      <span class="area-header-title">{{ $t('用户管理') }}</span>
    </div>
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container mb20">
          <el-input
            v-model="deptName"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            :placeholder="$t('部门名称')"
          />
        </div>
        <div v-loading="treeLoading" class="head-container" style="max-height: 560px;overflow: auto;">
          <el-tree
            v-if="type !== ''"
            ref="tree"
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :default-expand-all="type === 'tree'"
            :lazy="type !== 'tree'"
            :load="lazyLoad"
            node-key="id"
            :default-expanded-keys="expandedKeys"
            :indent="10"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node }" class="dept-class" :title="node.label">{{ node.label }}</span>
          </el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-form-item :label="$t('用户名称')" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              :placeholder="$t('用户名称')"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('登录名')" prop="userName">
            <el-input
              v-model="queryParams.userName"
              :placeholder="$t('登录名')"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('手机号码')" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              :placeholder="$t('手机号码')"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item :label="$t('状态')" prop="status">
            <el-select
              v-model="queryParams.status"
              :placeholder="$t('请选择')"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('创建时间')">
            <DatePicker
              v-model="dateRange"
              type="daterange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('搜索') }}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('重置') }}</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:edit']"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >{{ $t('新增') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:remove']"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >{{ $t('删除') }}</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:user:import']"
              type="info"
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >{{ $t('导入') }}
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-if="showSyncDingtalk"
              v-hasPermi="['system:user:edit']"
              type="info"
              icon="el-icon-refresh"
              size="mini"
              @click="syncDingTalk"
            >{{ $t('从钉钉同步') }}
            </el-button>
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          tooltip-effect="darkTable"
          :data="userList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column :label="$t('用户名称')" align="center" prop="nickName" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('登录名')" align="center" prop="userName" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('公司')" align="center" prop="company.deptName" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('部门')" align="center" prop="dept.deptName" :show-overflow-tooltip="true" />
          <el-table-column :label="$t('手机号码')" align="center" prop="phonenumber" width="120" />
          <el-table-column :label="$t('状态')" align="center" width="80">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column :label="$t('创建时间')" align="center" prop="createTime" width="130">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('操作')"
            align="center"
            width="180"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['system:user:edit']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >{{ $t('修改') }}
              </el-button>
              <el-button
                v-if="scope.row.userId !== 1"
                v-hasPermi="['system:user:remove']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >{{ $t('删除') }}
              </el-button>
              <el-button
                v-hasPermi="['system:user:resetPwd']"
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
              >{{ $t('重置') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="$t('用户')"
      :visible.sync="open"
      width="800px"
      custom-class="dialogNew"
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <el-form ref="form" class="dataForm" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('用户名称')" prop="nickName">
              <el-input v-model="form.nickName" :placeholder="$t('用户名称')" maxlength="50" show-word-limit>
                <template v-if="isHr" slot="append">
                  <a @click="selectHrList">{{ $t('关联人力资源') }}</a>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('登录名')" prop="userName">
              <el-input
                v-model="form.userName"
                :placeholder="$t('登录名')"
                clearable
                auto-complete="new-password"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.userId === undefined" :label="$t('用户密码')" prop="password">
              <el-input
                v-model="form.password"
                :placeholder="$t('用户密码')"
                type="password"
                clearable
                auto-complete="new-password"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('归属公司')" prop="companyId">
              <tree-select
                v-model="form.companyId"
                :default-expand-all="true"
                :data="companyOptions"
                node-key="id"
                :placeholder="$t('请选择')"
              >
                <label
                  slot="option-label"
                  slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                  :class="labelClassName"
                >
                  {{ $t(node.label) }}
                  <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
                </label>
              </tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('归属部门')" prop="deptId">
              <dept-select
                v-model="form.deptId"
                :default-expand-all="true"
                :data="deptOptions"
                :placeholder="$t('请选择')"
              >
                <label
                  slot="option-label"
                  slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                  :class="labelClassName"
                >
                  {{ $t(node.label) }}
                  <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
                </label>
              </dept-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('手机号码')" prop="phonenumber">
              <el-input v-model="form.phonenumber" :placeholder="$t('手机号码')" maxlength="11" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('邮箱')" prop="email">
              <el-input v-model="form.email" :placeholder="$t('邮箱')" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('用户标识')" prop="userKey">
              <el-input v-model="form.userKey" :placeholder="$t('用户标识')" :disabled="form.id" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('角色')" prop="roleIds">
              <el-select v-model="form.roleIds" filterable multiple :placeholder="$t('请选择')">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="$t(item.roleName)"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('用户性别')">
              <el-select v-model="form.sex" :placeholder="$t('请选择')">
                <el-option
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('岗位')">
              <el-select v-model="form.postIds" multiple :placeholder="$t('请选择')">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="$t(item.postName)"
                  :value="item.postId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('入职时间')" prop="entryTime">
              <DatePicker
                v-model="form.entryTime"
                type="date"
                :placeholder="$t('请选择')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('开始工作时间')" prop="beginJobTime">
              <DatePicker
                v-model="form.beginJobTime"
                type="date"
                :placeholder="$t('开始工作时间')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('首页模板')" prop="templateId">
              <el-select v-model="form.templateId" :placeholder="$t('请选择')">
                <el-option
                  v-for="(item, index) in templateOptions"
                  :key="index"
                  :label="$t(item.name)"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('状态')">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ $t(dict.dictLabel) }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('用户英文名')" prop="userEnglishName">
              <el-input
                v-model="form.userEnglishName"
                :placeholder="$t('用户英文名')"
                clearable
                auto-complete="new-password"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('备注')">
              <el-input v-model="form.remark" type="textarea" show-word-limit :maxlength="200" :placeholder="$t('备注')" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="area-header">
          <span class="area-header-title">{{ $t('用户部门') }}</span>
        </div>
        <el-table
          :data="form.deptTakeList"
          border
          class="nowrapTable formTable"
        >
          <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
            <template slot-scope="scope">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('部门')" align="center" prop="deptName" />
          <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['system:deptTake:remove']"
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="deleteDeptTake(scope.row)"
              >{{ $t('删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['system:deptTake:edit']"
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="addDeptTake"
            >{{ $t('新增') }}</el-button>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">{{ $t('取消') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('确定') }}</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="$t('用户')"
      :visible.sync="upload.open"
      width="400px"
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          {{ $t('将文件拖到此处，或') }}
          <em>{{ $t('上传') }}</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-checkbox v-model="upload.updateSupport" />
          {{ $t('是否更新已经存在的用户数据') }}
          <el-link type="primary" style="font-size:12px" @click="fetchTemplate">
            {{ $t('下载模板') }}
          </el-link>
          <!--<el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>-->
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red"> {{ $t('提示：仅允许导入“xls”或“xlsx”格式文件！') }}</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">{{ $t('取消') }}</el-button>
        <el-button type="primary" @click="submitFileForm">{{ $t('确定') }}</el-button>
      </div>
    </el-dialog>

    <!-- 用户多部门弹窗 -->
    <el-dialog title="用户部门" :visible.sync="deptTakeDialog">

      <el-form ref="deptTakeForm" :model="deptTakeForm" :rules="deptTakeRules" label-width="120px" class="dataForm">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('归属公司')" prop="companyId">
              <tree-select
                v-model="deptTakeForm.companyId"
                :default-expand-all="true"
                :data="companyOptions"
                :placeholder="$t('请选择')"
                node-key="id"
              >
                <label
                  slot="option-label"
                  slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }"
                  :class="labelClassName"
                >
                  {{ $t(node.label) }}
                  <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
                </label>
              </tree-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('任职部门')" prop="deptId">
              <tree-select v-model="deptTakeForm.deptId" node-key="id" :default-expand-all="true" :data="deptOptions" :placeholder="$t('请选择')">
                <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                  {{ $t(node.label) }}
                  <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
                </label>
              </tree-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDeptTake">{{ $t("取消") }}</el-button>
        <el-button type="primary" @click="submitDeptTake">{{ $t("确定") }}</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="$t('关联数据')"
      :visible.sync="openHr"
      custom-class="dialogNew"
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <hr-base-select-list ref="hrList" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  exportUser,
  resetUserPwd,
  changeUserStatus,
  importTemplate,
  getMenuKeyAndParentMenuKey, syncDingTalk
} from '@/api/system/user'
import { saveSysDeptTake, delSysDeptTake, listSysDeptTake } from '@/api/system/deptTake/sysDeptTake'
import { getToken } from '@/utils/auth'
import { listsDept, treeselect } from '@/api/system/dept'
import TreeSelect from '@/components/TreeSelect/index'
import { getAll } from '@/api/system/home/template/homeTemplate'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import hrBaseSelectList from '@/views/oa/hr/base/hrBaseSelectList'
import { getHrBase, saveHrBase } from '@/api/oa/hr/hrBase'
// import { getConfigKey } from '@/api/system/config'

export default {
  name: 'User',
  components: { TreeSelect, hrBaseSelectList },
  data() {
    return {
      // 遮罩层
      loading: true,
      treeLoading: true,
      // 是否关联人力资源
      isHr: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 公司树
      companyOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 用户多部门弹出层
      deptTakeDialog: false,
      openHr: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 首页模板
      templateOptions: [],
      // 要展开的层级
      expandedKeys: [],
      // 表单参数
      form: {},
      // 用于记录点击修改的时候当前row对象的信息
      formRow: {},
      defaultProps: {
        children: 'children',
        label: 'label',
        isLeaf: 'leaf'
      },
      deptTakeForm: {

      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/user/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      showSyncDingtalk: false,
      // 查询方式
      type: '',
      // 根节点
      firstNode: undefined,
      resolve: undefined,
      // 表单校验
      rules: {
        userName: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        userKey: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        entryTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        templateId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: this.$t('格式错误'),
            trigger: ['blur', 'change']
          },
          {
            required: true, message: this.$t('必填信息'), trigger: 'blur'
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: this.$t('格式错误'),
            trigger: 'blur'
          }
        ]
      }, deptTakeRules: {
        deptId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      if (this.type === 'table') {
        if (val) {
          if (this.timer) {
            clearTimeout(this.timer)
          }
          this.timer = setTimeout(() => {
            listsDept({ deptName: val }).then(res => {
              res.data.forEach(item => {
                item.leaf = true
              })
              this.deptOptions = res.data
              this.$refs.tree.root.setData(res.data)
            })
          }, 300)
        } else {
          this.refershTree()
        }
      } else {
        this.$refs.tree.filter(val)
      }
    }
  },
  created() {
    this.getConfigKey('dd.corpId').then(res => {
      if (res.msg) {
        this.showSyncDingtalk = true
      }
    })
    this.initMethod()
    this.getList()
    this.treeLoading = true
    // 获取布局类型
    if (this.$store.state.app.componentLayout) {
      this.$set(this, 'type', this.$store.state.app.componentLayout)
    } else {
      this.type = 'tree'
    }
    // 更新展示的节点名称
    if (this.$store.state.app.componentLayout === 'table') {
      this.defaultProps.label = 'deptName'
    } else {
      this.defaultProps.label = 'label'
    }
    this.treeLoading = false
    this.getTreeselect()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_user_sex').then(response => {
      this.sexOptions = response.data
    })
    this.getConfigKey('sys.user.initPassword').then(response => {
      this.initPassword = response.data
    })
    getAll().then(response => {
      this.templateOptions = response.data
    })
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.userList = response.rows
            this.total = response.total
            this.loading = false
            this.$store.dispatch('getSelTreeUser')
          }
      )
    },
    // 增加用户的多部门
    addDeptTake() {
      this.deptTakeDialog = true
    },
    /** 查询部门下拉树结构 */
     getTreeselect() {
      if (this.type === 'tree') {
        treeselect().then(response => {
          this.deptOptions = response.data
        })
      }
      var query = { 'deptType': 'GS' }
      treeselect(query).then(response => {
        this.companyOptions = response.data
      })
    },
    // 懒加载部门
    lazyLoad(node, resolve) {
      console.log(node)
      if (node.level === 0) {
        // 加载一级节点
        this.firstNode = node
        this.resolve = resolve
        this.loadFirstNode(resolve)
      }
      if (node.level > 0) {
        this.loadOtherNode(node, resolve)
      }
    },
    loadFirstNode(resolve) {
      listsDept({ parentId: '0', isSelectTop: '' }).then(res => {
        var nodeKeys = []
        res.data.forEach(item => {
          nodeKeys.push(item.id)
        })
        this.expandedKeys = nodeKeys
        resolve(res.data)
      })
    },
    loadOtherNode(node, resolve) {
       listsDept({ parentId: node.data.id }).then(res => {
         resolve(res.data)
       })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    refershTree() {
      console.log(this.deptOptions)
      this.deptOptions = []
      this.lazyLoad(this.firstNode, this.resolve)
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.getList()
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? this.$t('启用') : this.$t('停用')
      this.$confirm(this.$t('确认要') + text + ' ' + row.userName + '?', this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return changeUserStatus(row.userId, row.status)
      }).then(() => {
        this.msgSuccess(text + this.$t('成功'))
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
      this.$store.dispatch('getSelTreeUser')
    },
    // 删除 单个多部门信息
    deleteDeptTake(row) {
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delSysDeptTake(row.id)
      }).then(() => {
        // 重置修改页面。 把 formTakeList 重新查询
        const pa = { 'userId': row.userId }
        listSysDeptTake(pa).then(reponse => {
          this.form.deptTakeList = reponse.rows
        })
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {})
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancelDeptTake() {
      this.deptTakeDialog = false
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        companyId: undefined,
        userName: undefined,
        userEnglishName: undefined,
        nickName: undefined,
        beginJobTime: undefined,
        password: undefined,
        phonenumber: undefined,
        hrId: undefined,
        email: undefined,
        sex: undefined,
        status: '0',
        remark: undefined,
        postIds: [],
        roleIds: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getTreeselect()
      getUser().then(response => {
        this.postOptions = response.datas.posts
        this.roleOptions = response.datas.roles
        this.open = true
        // this.form.password = this.initPassword
        this.form.username = ''
        this.form.password = ''
        this.form.deptId = this.queryParams.deptId
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      const userId = row.userId || this.ids
      getUser(userId).then(response => {
        this.form = response.data
        this.postOptions = response.datas.posts
        this.roleOptions = response.datas.roles
        this.form.postIds = response.datas.postIds
        this.form.roleIds = response.datas.roleIds
        this.open = true
        this.form.password = ''
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt(row.userName + this.$t('新密码'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消')
      }).then(({ value }) => {
        resetUserPwd(row.userId, value).then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.$t('修改成功'))
          } else {
            this.msgError(response.msg)
          }
        })
      }).catch(() => {
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      let h = {}
      // 查询花名册是否关联
      if (this.isHr && this.form.hrId !== undefined && this.form.hrId !== null) {
        getHrBase(this.form.hrId).then(res => {
          console.log(res)
            if (res.data.userId !== null && res.data.userId !== undefined && res.data.userId !== '') {
              return this.msgError(this.$t('此用户已经关联'))
            }
          h = res.data
        })
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.userId !== undefined) {
            updateUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('修改成功'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('添加成功'))
                h.userId = response.data
                h.entryTime = this.form.entryTime
                if (this.isHr && this.form.hrId !== undefined && this.form.hrId !== null) {
                  saveHrBase(h).then(res => {
                    console.log(res)
                  })
                }
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        } else {
          this.locationError(document)
        }
      })
    },
    // 保存用户多部门
    submitDeptTake() {
      this.loading = true
      this.$refs['deptTakeForm'].validate(valid => {
        if (valid === true) {
          this.deptTakeForm.userId = this.form.userId
          saveSysDeptTake(this.deptTakeForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess(response.msg)
              // 重置修改页面。 把 formTakeList 重新查询
              const pa = { 'userId': this.form.userId }
              listSysDeptTake(pa).then(reponse => {
                this.form.deptTakeList = reponse.rows
              })
              this.deptTakeDialog = false
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
      this.loading = false
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return delUser(userIds)
      }).then(() => {
        this.getList()
        this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm(this.$t('是否确认导出所有用户数据项?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return exportUser(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = this.$t('导入')
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg)
      })
    },
    // 文件上传中处理
    handleFileUploadProgress() {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, this.$t('导入结果'), { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 下载模板
    fetchTemplate() {
      var href1 = window.location.href
      var href2 = this.$route.path
      var url = href1.substring(0, href1.indexOf(href2))
      window.location.href = url + '/template/userManagementImport.xlsx'
    },
    // 初始化信息
    initMethod() {
      // 判断是否需要加载用户选择按钮
      getMenuKeyAndParentMenuKey('hr_base_info', 'human_resources').then(res => {
        if (res.data !== undefined && res.data !== null) {
          this.isHr = true
        } else {
          this.isHr = false
        }
      })
    },
    selectHrList() {
      this.openHr = true
      setTimeout(() => {
        this.$refs.hrList.getList()
      })
    },
    syncDingTalk() {
      this.loading = true
      syncDingTalk().then(() => {
        this.msgSuccess(this.$t('同步成功'))
        this.getTreeselect()
        this.getList()
        this.loading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/.dept-class{
  font-size: 14px;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
